package com.util;

import com.util.AccessTokenUtil;
import com.util.JSTicketUtil;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import java.text.SimpleDateFormat;
import java.util.Date;

public class WeiXinUtil {

    private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code";


    public static AccessTokenUtil getToken() throws IOException {
        AccessTokenUtil token = new AccessTokenUtil();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwe382c68e1b4882d7&corpsecret=CbjixI5DrLTBL69tgeHKB9UjYBeE7Cc51kAdGOcVDsk";
        JSONObject jsonObj = doGetStr(url);
        if (!StringUtils.isEmpty(jsonObj)) {
            token.setToken(jsonObj.getString("access_token"));
            token.setExpiresIn(jsonObj.getInt("expires_in"));
        }
        return token;
    }

    public static JSTicketUtil getJsTicket(String access_token) throws IOException {
        JSTicketUtil ticketObj = new JSTicketUtil();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + access_token;
        JSONObject jsonObj = doGetStr(url);
        if (!StringUtils.isEmpty(jsonObj)) {
            ticketObj.setTicket(jsonObj.getString("ticket"));
            ticketObj.setErrCode(jsonObj.getInt("errcode"));
            ticketObj.setErrMsg(jsonObj.getString("errmsg"));
            ticketObj.setExpiresIn(jsonObj.getInt("expires_in"));
        }
        return ticketObj;
    }

    public static JSTicketUtil getAgentJsTicket(String access_token) throws IOException {
        JSTicketUtil ticketObj = new JSTicketUtil();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?type=agent_config&access_token=" + access_token;
        JSONObject jsonObj = doGetStr(url);
        if (!StringUtils.isEmpty(jsonObj)) {
            ticketObj.setTicket(jsonObj.getString("ticket"));
            ticketObj.setErrCode(jsonObj.getInt("errcode"));
            ticketObj.setErrMsg(jsonObj.getString("errmsg"));
            ticketObj.setExpiresIn(jsonObj.getInt("expires_in"));
        }
        return ticketObj;
    }

    /**
     * 获取时间戳(秒)
     */
    public static String getTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 获取当前时间 yyyyMMddHHmmss
     */
    public static String getCurrTime() {
        Date now = new Date();
        SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = outFormat.format(now);
        return s;
    }

    /**
     * 生成随机字符串
     */
    public static String getNonceStr() {
        String currTime = getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = buildRandom(4) + "";
        return strTime + strRandom;
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     *
     * @param length int设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }


    public static JSONObject doGetStr(String url) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);//HttpGet使用Get方式发送请求URL
        JSONObject jsonObj = null;
        HttpResponse res = httpClient.execute(httpGet);//使用httpClient从Client执行httpGet的请求
        HttpEntity entity = res.getEntity();//从HttpResponse中获取结果
        if (!StringUtils.isEmpty(entity)) {
            String result = EntityUtils.toString(entity, "utf-8");
            jsonObj = JSONObject.fromObject(result);//字符串类型转换为JSON对象
        }
        return jsonObj;
    }

    public static JSONObject doPostStr(String url, String outStr) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);//HttpGet使用Post方式发送请求URL
        JSONObject jsonObj = null;
        httpPost.setEntity(new StringEntity(outStr, "utf-8"));//使用setEntity方法,将传进来的参数放进请求
        HttpResponse res = httpClient.execute(httpPost);
        HttpEntity entity = res.getEntity();//从HttpResponse中获取结果
        if (!StringUtils.isEmpty(entity)) {
            String result = EntityUtils.toString(entity, "utf-8");
            jsonObj = JSONObject.fromObject(result);//字符串类型转换为JSON对象
        }
        return jsonObj;
    }
}
